import request from '../utils/request'
import type { 
  Order, 
  PaymentParams, 
  PaymentResponse, 
  RefundParams, 
  RefundResponse 
} from '../types/api'

class OrderService {
  async getOrders(params?: {
    page?: number
    pageSize?: number
    status?: Order['status']
    startDate?: string
    endDate?: string
  }): Promise<{
    orders: Order[]
    total: number
    hasMore: boolean
  }> {
    const response = await request.get<{
      orders: Order[]
      total: number
      hasMore: boolean
    }>('/orders', params)
    
    return response.data
  }

  async getOrderDetail(orderId: string): Promise<Order> {
    const response = await request.get<Order>(`/orders/${orderId}`)
    return response.data
  }

  async cancelOrder(orderId: string, reason?: string): Promise<void> {
    await request.put(`/orders/${orderId}/cancel`, { reason })
  }

  async createPayment(params: PaymentParams): Promise<PaymentResponse> {
    const response = await request.post<PaymentResponse>('/payments/create', params)
    return response.data
  }

  async queryPaymentStatus(orderId: string): Promise<{
    status: 'pending' | 'paid' | 'failed' | 'cancelled'
    paymentTime?: string
  }> {
    const response = await request.get<{
      status: 'pending' | 'paid' | 'failed' | 'cancelled'
      paymentTime?: string
    }>(`/payments/query/${orderId}`)
    
    return response.data
  }

  async createRefund(params: RefundParams): Promise<RefundResponse> {
    const response = await request.post<RefundResponse>('/refunds/create', params)
    return response.data
  }

  async getRefundStatus(refundId: string): Promise<{
    status: 'processing' | 'success' | 'failed'
    refundTime?: string
    failReason?: string
  }> {
    const response = await request.get<{
      status: 'processing' | 'success' | 'failed'
      refundTime?: string
      failReason?: string
    }>(`/refunds/${refundId}`)
    
    return response.data
  }
}

export const orderService = new OrderService()
export default orderService